
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;


class Computer {
public:
    Computer()
    : _brand(nullptr)
    , _price(0)
    { cout << "Computer()" << endl; }

    Computer(const char * brand, double price)
    : _brand(new char[strlen(brand) + 1]())
    , _price(price)
    {
        cout << "Computer(const char*, double)" << endl;
        strcpy(_brand, brand);
    }

    
    //必须手动提供
    Computer(const Computer & rhs)
    : _brand(new char[strlen(rhs._brand) + 1]())
    , _price(rhs._price)
    {   
        cout << "Computer(const Computer&)" << endl;    
        strcpy(_brand, rhs._brand);//深拷贝
    }

    //系统提供的赋值运算符函数
    //很显然是不能满足需求
    // pc2 = pc1;   => pc2.operator=(pc1);
    /* Computer & operator=(const Computer & rhs) */
    /* { */
    /*     cout << "Computer & operator=(const Computer &)" << endl; */
    /*     this->_brand = rhs._brand; */
    /*     this->_price = rhs._price; */
    /*     return *this; */
    /* } */

    Computer & operator=(const Computer & rhs)
    {
        cout << "Computer & operator=(const Computer&)" << endl;
        if(this != &rhs) {//1. 自复制
            delete [] _brand;//2. 回收左操作数的空间
            _brand = new char[strlen(rhs._brand) + 1]();
            strcpy(_brand, rhs._brand);//3. 深拷贝

            _price = rhs._price;
        }
        return *this;//4. return *this
    }

    void print() 
    {
        if(_brand) {
            printf("brand's address: %p\n", _brand);
            cout << "brand:" << _brand << endl;
            cout << "price:" << _price << endl;
        }
    }

    ~Computer()
    {
        cout << "~Computer()" << endl;
        if(_brand) {
            delete [] _brand;
            _brand = nullptr;
        }
    }

    

private:
    char * _brand;
    double _price;
};

void test0()
{
    Computer pc1("Huawei matebook", 7777);  
    cout << "pc1:";
    pc1.print();
    Computer pc2("Xiaomi", 8888);
    cout << "pc2:";
    pc2.print();

    cout << "\n执行赋值操作:\n";
    pc2 = pc1;
    cout << "pc1:";
    pc1.print();
    cout << "pc2:";
    pc2.print();

    pc2 = pc2;//自复制
    cout << "pc2:";
    pc2.print();

}


int main()
{
    test0();
    return 0;
}

